package web;

import cn.hutool.core.date.DateTime;
import com.wf.captcha.utils.CaptchaUtil;
import dao.LoginDao;
import dao.RegisterDao;
import entity.User;
import utils.FileDownLoad;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

@WebServlet("/register")
public class RegisServer extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/Register.html").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8;");
        String captcha = req.getParameter("captcha");
        System.out.println(captcha);
        if (CaptchaUtil.ver(captcha, req)) {
            CaptchaUtil.clear(req);
            String username = req.getParameter("username1");
            String name = req.getParameter("name");
            String password = req.getParameter("password2");
            String password2 = req.getParameter("password3");
            String birth = req.getParameter("birth");
            String phone = req.getParameter("phone");
            String email = req.getParameter("email");

            // 从表单中获取的用户名和密码与预定义的用户名和密码进行比较
            if (username != null && password != null) {
                if (password.equals(password2)) {
                    User users = null;
                    try {
                        users = new LoginDao().selectByUsernameAndPassword(username, password);
                        if (users == null) {
                            try {
                                new RegisterDao().addUser(username,name, password2, birth, phone,email);
                                System.out.println("注册成功");
                                resp.sendRedirect(req.getContextPath() + "/login");
                            } catch (SQLException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            resp.getWriter().write("<h3 style='color:red;'>账户已存在</h3>,<a href='/login'>请登录</a>");
                        }
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    resp.getWriter().write("<h3 style='color:red;'>两次密码不一致</h3>,<a href='/register'>请重新注册</a>");
                }
            }
        }
    }
}

